package com.squareup.picasso;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.Pair;

import com.bytedance.frameworks.baselib.network.dispatcher.AbsRequest;
import com.squareup.picasso.Downloader.ResponseException;
import com.squareup.picasso.NetworkRequestHandler.ContentLengthException;
import com.squareup.picasso.Picasso.LoadedFrom;
import com.squareup.picasso.Picasso.Priority;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

import inline.ScreenshotListener;
import pl.droidsonroids.gif.GifDrawable;

final class BitmapHunter implements Runnable {
    public enum CompressFormat {
        JPEG(0),
        PNG(1),
        WEBP(2),
        GIF(3);

        final int nativeInt;

        CompressFormat(int nativeInt) {
            this.nativeInt = nativeInt;
        }
    }


    final Picasso picasso;
    final String key;
    final Request data;
    final int d = 0;
    int errorResOd;
    final RequestHandler requestHandler;
    Action action;
    List<Action> actions;
    Drawable result;
    AbsRequest absRequest;
    LoadedFrom loadedFrom;
    Exception exception;
    int retryCount;
    Priority priority;
    private static final Object DECODE_LOCK = new Object();
    private static final ThreadLocal sThreadLocal = new ThreadLocal() {
        @Override
        protected final Object initialValue() {
            return new StringBuilder("Picasso-");
        }
    };
    private static final AtomicInteger counter = new AtomicInteger();
    private static final RequestHandler EMPTY_REQUEST_HANDLER = new EmptyRequestHandler();
    private Dispatcher dispatcher;
    private Cache cache;
    private BitmapDiskLruCache bitmapDiskLruCache;
    private Stats stats;
    private int w;

    private BitmapHunter(Picasso picasso, Dispatcher dispatcher, Cache cache, BitmapDiskLruCache bitmapDiskLruCache, Stats stats, Action action, RequestHandler requestHandler) {
        counter.incrementAndGet();
        this.picasso = picasso;
        this.dispatcher = dispatcher;
        this.cache = cache;
        this.bitmapDiskLruCache = bitmapDiskLruCache;
        this.stats = stats;
        this.action = action;
        this.key = action.key;
        this.data = action.data;
        this.priority = action.data.priority;
        this.errorResOd = action.errorResId;
        this.requestHandler = requestHandler;
        this.retryCount = requestHandler.getRetryCount();
    }

    private static Bitmap applyCustomTransformations(List<ScreenshotListener> transformations, Bitmap result) {
        int size = transformations.size();
        int index = 0;
        ScreenshotListener transformation;
        Bitmap bitmap;
        for (bitmap = result; index < size; bitmap = result) {
            transformation = transformations.get(index);
            try {
                result = transformation.transform();
                if (result != null) {
                    if (result == bitmap && bitmap.isRecycled()) {
                        final ScreenshotListener finalTransformation = transformation;
                        Picasso.dispatcherHandler.post(new Runnable() {
                            @Override
                            public void run() {
                                throw new IllegalStateException("Transformation " + finalTransformation.key() + " returned input Bitmap but recycled it.");
                            }
                        });
                        return null;
                    }
                    if (result != bitmap && !bitmap.isRecycled()) {
                        final ScreenshotListener finalTransformation1 = transformation;
                        Picasso.dispatcherHandler.post(new Runnable() {
                            @Override
                            public void run() {
                                throw new IllegalStateException("Transformation " + finalTransformation1.key() + " mutated input Bitmap but failed to recycle the original.");
                            }
                        });
                        return null;
                    }
                    ++index;
                    continue;
                }
            } catch (final RuntimeException runtimeException) {
                final ScreenshotListener finalTransformation2 = transformation;
                Picasso.dispatcherHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        throw new RuntimeException("Transformation " + finalTransformation2.key() + " crashed with exception.", runtimeException);
                    }
                });
                return null;
            }

            final StringBuilder stringBuilder = new StringBuilder("Transformation ").append(transformation.key()).append(" returned null after ").append(index).append(" previous transformation(s).\n\nTransformation list:\n");
            Iterator<ScreenshotListener> transformationIterator = transformations.iterator();
            while (transformationIterator.hasNext()) {
                stringBuilder.append(transformationIterator.next().key()).append('\n');
            }
            Picasso.dispatcherHandler.post(new Runnable() {
                @Override
                public final void run() {
                    throw new NullPointerException(stringBuilder.toString());
                }
            });
            return null;

        }

        return bitmap;

    }

    static BitmapHunter forRequest(Picasso arg8, Dispatcher arg9, Cache arg10, BitmapDiskLruCache arg11, Stats arg12, Action arg13) {
        BitmapHunter v0_1;
        Request v1 = arg13.data;
        List v2 = arg8.requestHandlerList;
        int v0 = 0;
        int v3 = v2.size();
        while (true) {
            if (v0 < v3) {
                Object v7 = v2.get(v0);
                if (((RequestHandler) v7).canHandleRequest(v1)) {
                    v0_1 = new BitmapHunter(arg8, arg9, arg10, arg11, arg12, arg13, ((RequestHandler) v7));
                } else {
                    ++v0;
                    continue;
                }
            } else {
                break;
            }

            return v0_1;
        }

        return new BitmapHunter(arg8, arg9, arg10, arg11, arg12, arg13, EMPTY_REQUEST_HANDLER);
    }

    private static boolean a(boolean arg1, int arg2, int arg3, int arg4, int arg5) {
        return !arg1 || arg2 > arg4 || arg3 > arg5;
    }

    final void detach(Action action) {
        Priority v1_1;
        boolean v0;
        int v1 = 1;
        int v2 = 0;
        if (this.action == action) {
            this.action = null;
            v0 = true;
        } else if (this.actions != null) {
            v0 = this.actions.remove(action);
        } else {
            v0 = false;
        }

        if ((v0) && action.data.priority == this.priority) {
            Priority v3 = Priority.LOW;
            int v0_1 = this.actions == null || (this.actions.isEmpty()) ? 0 : 1;
            if (this.action == null && v0_1 == 0) {
                v1 = 0;
            }

            if (v1 != 0) {
                v1_1 = this.action != null ? this.action.data.priority : v3;
                if (v0_1 == 0) {
                } else {
                    int v3_1 = this.actions.size();
                    while (v2 < v3_1) {
                        Priority v0_2 = this.actions.get(v2).data.priority;
                        if (v0_2.ordinal() <= v1_1.ordinal()) {
                            v0_2 = v1_1;
                        }

                        ++v2;
                        v1_1 = v0_2;
                    }
                }
            } else {
                v1_1 = v3;
            }
            this.priority = v1_1;
        }
    }

    final boolean cancel() {
        int v0;
        boolean v1 = true;
        if (this.absRequest != null) {
            this.absRequest.cancel();
            v0 = 1;
        } else {
            v0 = 0;
        }

        if (this.action == null) {
            if (this.actions != null && !this.actions.isEmpty()) {
                return false;
            }

            if (this.absRequest == null) {
                return false;
            }

            if (v0 == 0) {
                return false;
            }
        } else {
            v1 = false;
        }

        return v1;
    }

    final boolean isCancelled() {
        return this.absRequest != null && this.absRequest.isCanceled();
    }

    private Drawable hunt() throws IOException {
        int v10_2;
        float v5_6;
        float v8_2;
        int v16;
        int v15;
        Matrix v7_2;
        int v4_5;
        int v9;
        int v6_2;
        int v13;
        OutputStream v3_12;
        Bitmap.CompressFormat v3_9;
        GifDrawable v3_8;
        GifDrawable v5_2 = null;
        Object v4_1;
        Bitmap v3_5;
        Pair v2_6;
        CompressFormat v11;
        BitmapFactory.Options v4;
        long v8;
        MarkableInputStream v3_3;
        Request v2_5;
        RequestHandler.Result v6;
        Request v3_1;
        BitmapDrawable v5_1;
        Drawable v5 = null;
        Object v2_3 = null;
        if (MemoryPolicy.shouldReadFromMemoryCache(0)) {
            v2_3 = this.cache.get(this.key);
            if (v2_3 != null) {
                this.stats.dispatchCacheHit();
                this.loadedFrom = LoadedFrom.MEMORY;
                v5_1 = new BitmapDrawable(this.picasso.context.getResources(), (Bitmap) v2_3);
                return v5_1;
            }
        }

        RequestHandler.Result v2_1 = null;
        if (DiskCachePolicy.shouldReadFromDiskCache(0)) {
            InputStream v3 = this.bitmapDiskLruCache.b(this.key);
            if (v3 != null) {
                v2_1 = new RequestHandler.Result(v3, LoadedFrom.DISK);
            }
        }

        if (v2_1 == null) {
            v3_1 = this.data;
            int v2_2 = this.retryCount == 0 ? NetworkPolicy.OFFLINE.index : this.errorResOd;
            v3_1.networkPolicy = v2_2;
            v6 = this.requestHandler.load(this.data);
        } else {
            v6 = v2_1;
        }

        Object v3_2 = null;
        if (v6 == null) {

        } else {
            this.loadedFrom = v6.loadedFrom;
            this.w = v6.exifRotation;
            if (v6.bitmap != null) {
                v2_3 = v6.bitmap;
            } else {
                InputStream v7 = v6.inputStream;
                v2_5 = this.data;
                v3_3 = new MarkableInputStream(v7);
                v8 = v3_3.savePosition(65536);
                v4 = RequestHandler.createBitmapOptions(v2_5);
                boolean v10 = RequestHandler.inJustDecodeBounds(v4);
                v11 = Utils.c(((InputStream) v3_3));
                v3_3.reset(v8);
                if (v11 == CompressFormat.WEBP) {
                    byte[] v3_4 = Utils.b(((InputStream) v3_3));
                    if (v10) {
                        BitmapFactory.decodeByteArray(v3_4, 0, v3_4.length, v4);
                        RequestHandler.calculateInSampleSize(v2_5.targetWidth, v2_5.targetHeight, v4, v2_5);
                    }
                    v2_6 = new Pair(BitmapFactory.decodeByteArray(v3_4, 0, v3_4.length, v4), v11);
                } else {
                    if (v11 != CompressFormat.GIF) {
                        if (v10) {
                            Rect v10_1 = null;
                            BitmapFactory.decodeStream(((InputStream) v3_3), v10_1, v4);
                            RequestHandler.calculateInSampleSize(v2_5.targetWidth, v2_5.targetHeight, v4, v2_5);
                            v3_3.reset(v8);
                            label_262:
                            v3_5 = BitmapFactory.decodeStream(((InputStream) v3_3), null, v4);
                            if (v3_5 == null) {
                                throw new IOException("Failed to decode stream.");
                            }
                            v2_6 = new Pair(v3_5, v11);
                        } else {
                            v3_5 = BitmapFactory.decodeStream(((InputStream) v3_3), null, v4);
                            if (v3_5 == null) {
                                throw new IOException("Failed to decode stream.");
                            }
                            v2_6 = new Pair(v3_5, v11);
                        }
                    } else {
                        v2_6 = new Pair(v3_3, v11);
                    }
                }

                v4_1 = v2_6.first;
                v2_3 = v2_6.second;
                if (v2_3 != CompressFormat.GIF) {
                    v3_8 = v5_2;
                } else {
                    File v3_6 = this.bitmapDiskLruCache.getCacheFile(this.key, (InputStream) v4_1);
                    if (v3_6 == null) {
                        v3_8 = v5_2;
                    } else {
                        String v8_1 = v3_6.getAbsolutePath();
                        v5_2 = null;
                        if (v8_1 == null) {
                            v3_8 = v5_2;
                        } else {
                            try {
                                v3_8 = new GifDrawable(v8_1);
                            } catch (Throwable v3_7) {
                                v3_8 = v5_2;
                            }
                        }
                    }
                }
                Utils.closeQuietly(v7);
                v5_2 = v3_8;
                v3_2 = v2_3;
                v2_3 = v4_1;
            }
        }

        if ((v2_3 instanceof Bitmap)) {
            if (v6.loadedFrom == LoadedFrom.NETWORK && (DiskCachePolicy.shouldWriteToDiskCache(0))) {
                BitmapDiskLruCache v5_3 = this.bitmapDiskLruCache;
                String v4_2 = this.key;
                if (v2_3 == null) {

                } else {
                    if (v3_2 != null) {
                        String v6_1 = com.bytedance.common.utility.aa.md5(v4_2);
                        Bitmap.CompressFormat v4_3 = Bitmap.CompressFormat.PNG;
                        switch (((CompressFormat) v3_2)) {
                            case WEBP: {
                                v3_9 = Bitmap.CompressFormat.WEBP;
                                break;
                            }
                            case PNG: {
                                v3_9 = Bitmap.CompressFormat.PNG;
                                break;
                            }
                            case JPEG: {
                                v3_9 = Bitmap.CompressFormat.JPEG;
                                break;
                            }
                            default: {
                                v3_9 = v4_3;
                                break;
                            }
                        }

                        if (v5_3.diskLruCache == null) {
                        } else {
                            OutputStream v4_4 = null;
                            DiskLruCache.Snapshot v7_1 = v5_3.diskLruCache.get(v6_1);
                            if (v7_1 == null) {
                                DiskLruCache.Editor v5_4 = v5_3.diskLruCache.edit(v6_1);
                                if (v5_4 != null) {
                                    v4_4 = v5_4.newOutputStream(0);
                                    ((Bitmap) v2_3).compress(v3_9, 100, v4_4);
                                    v5_4.commit();
                                    v4_4.close();
                                    v3_12 = v4_4;
                                } else {
                                    v3_12 = v4_4;
                                }
                            } else {
                                v7_1.ins[0].close();
                                v3_12 = v4_4;
                            }
                            if (v3_12 != null) {
                                try {
                                    v3_12.close();
                                } catch (IOException v3_11) {
                                }
                            }
                        }
                    }
                }
            }
            this.stats.processBitmap((Bitmap) v2_3, 2);
            v3_1 = this.data;
            int v3_13 = (v3_1.needsMatrixTransform()) || (v3_1.hasCustomTransformations()) ? 1 : 0;
            if (v3_13 != 0 || this.w != 0) {
                Object v12 = DECODE_LOCK;
                synchronized (v12) {
                    try {
                        if ((this.data.needsMatrixTransform()) || this.w != 0) {
                            Request v5_5 = this.data;
                            v13 = this.w;
                            v6_2 = ((Bitmap) v2_3).getWidth();
                            v9 = ((Bitmap) v2_3).getHeight();
                            boolean v14 = v5_5.l;
                            v3_13 = 0;
                            v4_5 = 0;
                            v7_2 = new Matrix();
                            int v5_7;
                            if (v5_5.needsMatrixTransform()) {
                                v15 = v5_5.targetWidth;
                                v16 = v5_5.targetHeight;
                                v8_2 = v5_5.rotationDegrees;
                                if (v8_2 != 0f) {
                                    if (v5_5.hasRotationPivot) {
                                        v7_2.setRotate(v8_2, v5_5.rotationPivotX, v5_5.rotationPivotY);
                                    } else {
                                        v7_2.setRotate(v8_2);
                                    }
                                }

                                if (!v5_5.centerCrop) {
                                    if (v5_5.centerInside) {
                                        v5_6 = (((float) v15)) / (((float) v6_2));
                                        v8_2 = (((float) v16)) / (((float) v9));
                                        if (v5_6 >= v8_2) {
                                            v5_6 = v8_2;
                                        }

                                        if (BitmapHunter.a(v14, v6_2, v9, v15, v16)) {
                                            v7_2.preScale(v5_6, v5_6);
                                        }
                                        v5_7 = v6_2;
                                        v6_2 = v9;
                                    } else if (v15 == 0 && v16 == 0) {
                                        v5_7 = v6_2;
                                        v6_2 = v9;
                                    } else if (v15 == v6_2 && v16 == v9) {
                                        v5_7 = v6_2;
                                        v6_2 = v9;
                                    } else {
                                        if (v15 != 0) {
                                            v8_2 = (((float) v15)) / (((float) v6_2));
                                        } else {
                                            v8_2 = (((float) v16)) / (((float) v9));
                                        }
                                        v5_6 = v16 != 0 ? (((float) v16)) / (((float) v9)) : (((float) v15)) / (((float) v6_2));
                                        if (!BitmapHunter.a(v14, v6_2, v9, v15, v16)) {

                                        } else {
                                            v7_2.preScale(v8_2, v5_6);
                                        }
                                        v5_7 = v6_2;
                                        v6_2 = v9;
                                    }
                                } else {
                                    v8_2 = (((float) v15)) / (((float) v6_2));
                                    v5_6 = (((float) v16)) / (((float) v9));
                                    float v10_3;
                                    int v8_3;
                                    float v11_1;
                                    if (v8_2 > v5_6) {
                                        v10_2 = ((int) Math.ceil(((double) ((((float) v9)) * (v5_6 / v8_2)))));
                                        v5_7 = (v9 - v10_2) / 2;
                                        v11_1 = v8_2;
                                        v8_3 = v10_2;
                                        v10_3 = (((float) v16)) / (((float) v10_2));
                                        v4_5 = v5_7;
                                        v5_7 = v6_2;
                                    } else {
                                        double v10_4 = ((double) ((((float) v6_2)) * (v8_2 / v5_6)));
                                        v10_2 = ((int) Math.ceil(v10_4));
                                        v3_13 = (v6_2 - v10_2) / 2;
                                        v11_1 = (((float) v15)) / (((float) v10_2));
                                        v8_3 = v9;
                                        int v17 = v10_2;
                                        v10_3 = v5_6;
                                        v5_7 = v17;
                                    }
                                    if (BitmapHunter.a(v14, v6_2, v9, v15, v16)) {
                                        v7_2.preScale(v11_1, v10_3);
                                    }
                                    v6_2 = v8_3;
                                }
                            } else {
                                v5_7 = v6_2;
                                v6_2 = v9;
                            }
                            if (v13 != 0) {
                                v7_2.preRotate(((float) v13));
                            }

                            v3_5 = Bitmap.createBitmap((Bitmap) v2_3, v3_13, v4_5, v5_7, v6_2, v7_2, true);
                            if (v3_5 != v2_3) {
                                ((Bitmap) v2_3).recycle();
                                v2_3 = v3_5;
                            }
                        }
                        if (this.data.hasCustomTransformations()) {
                            v2_3 = BitmapHunter.applyCustomTransformations(this.data.transformations, (Bitmap) v2_3);
                        }
                        if (v2_3 == null) {
                            return new BitmapDrawable(this.picasso.context.getResources(), (Bitmap) v2_3);
                        }
                        this.stats.processBitmap((Bitmap) v2_3, 3);
                    } catch (Throwable v2_4) {
                    }
                }
            }
            return new BitmapDrawable(this.picasso.context.getResources(), (Bitmap) v2_3);
        }

        return v5_2;
    }

    public final void run() {
        try {
            String v3 = data.uri != null ? String.valueOf(data.uri.getPath()) : Integer.toHexString(data.resourceId);
            Object v2_7 = BitmapHunter.sThreadLocal.get();
            ((StringBuilder) v2_7).ensureCapacity(v3.length() + 8);
            ((StringBuilder) v2_7).replace(8, ((StringBuilder) v2_7).length(), v3);
            Thread.currentThread().setName(((StringBuilder) v2_7).toString());
            this.result = this.hunt();
            if (this.result == null) {
                this.dispatcher.dispatchFailed(this);
            } else {
                this.dispatcher.handler.sendMessage(this.dispatcher.handler.obtainMessage(4, this));
            }
        } catch (OutOfMemoryError v2_2) {
            StringWriter stringWriter = new StringWriter();
            StatsSnapshot statsSnapshot = new StatsSnapshot(this.stats.cache.maxSize(), this.stats.cache.size(), this.stats.c, this.stats.cacheHits, this.stats.totalTransformedBitmapSize, this.stats.f, this.stats.totalOriginalBitmapSize, this.stats.averageTransformedBitmapSize, this.stats.i, this.stats.averageOriginalBitmapSize, this.stats.transformedBitmapCount, this.stats.cacheMisses, this.stats.originalBitmapCount, System.currentTimeMillis());
            PrintWriter printWriter = new PrintWriter(stringWriter);
            printWriter.println("===============BEGIN PICASSO STATS ===============");
            printWriter.println("Memory Cache Stats");
            printWriter.print("  Max Cache Size: ");
            printWriter.println(statsSnapshot.maxSize);
            printWriter.print("  Cache Size: ");
            printWriter.println(statsSnapshot.size);
            printWriter.print("  Cache % Full: ");
            printWriter.println(((int) Math.ceil(((double) ((((float) statsSnapshot.size)) / (((float) statsSnapshot.maxSize)) * 100f)))));
            printWriter.print("  Cache Hits: ");
            printWriter.println(statsSnapshot.cacheHits);
            printWriter.print("  Cache Misses: ");
            printWriter.println(statsSnapshot.cacheMisses);
            printWriter.println("Network Stats");
            printWriter.print("  Download Count: ");
            printWriter.println(statsSnapshot.downloadCount);
            printWriter.print("  Total Download Size: ");
            printWriter.println(statsSnapshot.totalDownloadSize);
            printWriter.print("  Average Download Size: ");
            printWriter.println(statsSnapshot.averageDownloadSize);
            printWriter.println("Bitmap Stats");
            printWriter.print("  Total Bitmaps Decoded: ");
            printWriter.println(statsSnapshot.originalBitmapCount);
            printWriter.print("  Total Bitmap Size: ");
            printWriter.println(statsSnapshot.totalOriginalBitmapSize);
            printWriter.print("  Total Transformed Bitmaps: ");
            printWriter.println(statsSnapshot.transformedBitmapCount);
            printWriter.print("  Total Transformed Bitmap Size: ");
            printWriter.println(statsSnapshot.totalTransformedBitmapSize);
            printWriter.print("  Average Bitmap Size: ");
            printWriter.println(statsSnapshot.averageOriginalBitmapSize);
            printWriter.print("  Average Transformed Bitmap Size: ");
            printWriter.println(statsSnapshot.averageTransformedBitmapSize);
            printWriter.println("===============END PICASSO STATS ===============");
            printWriter.flush();
            this.exception = new RuntimeException(stringWriter.toString(), v2_2);
            this.dispatcher.dispatchFailed(this);
        } catch (ContentLengthException v2_4) {
            this.exception = v2_4;
            this.dispatcher.dispatchRetry(this);
        } catch (ResponseException v2_5) {
            if (!v2_5.localCacheOnly || v2_5.responseCode != 504) {
                this.exception = v2_5;
            }
            this.dispatcher.dispatchFailed(this);
        } catch (IOException v2_3) {
            this.exception = ((Exception) v2_3);
            this.dispatcher.dispatchRetry(this);
        } catch (Exception v2_1) {
            this.exception = v2_1;
            this.dispatcher.dispatchFailed(this);
        } finally {
            Thread.currentThread().setName("Picasso-Idle");
        }

    }
}

